'use strict';

const conn = require('../../../libs/Conn');

module.exports = async function (params) {
    /*排序*/
    let orderBySql = ``;
    if(params.sort&&params.dir){
        switch (params.sort) {
            case 'user_name':
                orderBySql = `ORDER BY uf.user_name ${params.dir}`;
                break;
            case 'department_name':
                orderBySql = `ORDER BY df.department_name ${params.dir}`;
                break;
            case 'login_name':
                orderBySql = `ORDER BY uf.login_name ${params.dir}`;
                break;
            case 'group_name':
                orderBySql = `ORDER BY ug.group_name ${params.dir}`;
                break;
            case 'enable':
                orderBySql = `ORDER BY uf.enable ${params.dir}`;
                break;
        }
    }
    /*分页*/
    let pageSql = `LIMIT ${params.pageNum>1?((params.pageNum-1)*10):0},10;SELECT FOUND_ROWS() AS count`;

    let querySql = `SELECT
                        SQL_CALC_FOUND_ROWS
                        uf.user_id,
                        uf.user_name,
                        uf.login_name,
                        uf.enable,
                        ug.group_id,
                        ug.group_name,
                        df.department_id,
                        df.department_name,
                        uf.mobile
                    FROM
                        user_file uf
                    LEFT JOIN user_group ug ON uf.group_id = ug.group_id AND ug.delete_sign = 1
                    LEFT JOIN department_file df ON df.department_id = ug.department
                    WHERE
                        uf.delete_sign = 1 AND uf.group_id != 1  ${orderBySql} ${pageSql}`;

    let rec = await conn(querySql);
    let pageNum = Math.ceil(rec[1][0].count/10);
    for(let data in rec[0]){
        switch (rec[0][data].enable) {
            case 1:
                rec[0][data].enable_char = '启用';
                break;
            case 2:
                rec[0][data].enable_char = '禁用';
                break;
        }
    }
    if(rec[0].length>0){
        rec[0][0].dataTotal = rec[1][0].count;
        rec[0][0].pageTotal = pageNum;
        rec[0][0].pageNum = params.pageNum;
    }
    return {success: true, data: rec[0]};

};